package com.test.mchelepesa.util_rice.analytics_rice.util_rice

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustAttribution
import com.adjust.sdk.AdjustConfig
import com.adjust.sdk.AdjustEvent
import com.adjust.sdk.LogLevel
import com.google.gson.Gson
import com.test.mchelepesa.bean_rice.StaticConfig_rice
import com.test.mchelepesa.constant_rice.Constant_rice
import com.test.mchelepesa.constant_rice.Constant_rice.AJ_EVENT_APPLY
import com.test.mchelepesa.constant_rice.Constant_rice.AJ_EVENT_REGISTER
import com.test.mchelepesa.constant_rice.Constant_rice.AJ_TOKEN
import com.test.mchelepesa.constant_rice.Url_rice
import com.test.mchelepesa.util_rice.StringUtil_rice
import com.test.mchelepesa.util_rice.analytics_rice.bean_rice.ParamAdjustInstall
import com.test.mchelepesa.util_rice.analytics_rice.event_rice.IAnalyticsEvent_rice
import com.test.mchelepesa.util_rice.analytics_rice.http_rice.HttpHelper_rice

object AdjustUtil_rice {

    /** 归因信息 */
    var adjsutAttribution: ParamAdjustInstall? = null

    /**
     * 初始化Adjust模块
     * 按配置需要来初始化
     *
     * @param context Application
     */
    fun init(context: Application) {

        if (AJ_TOKEN.isBlank()) throw Exception("Error: Adjust Token must no be null!")
        if (AJ_EVENT_REGISTER.isBlank()) throw Exception("Error: Adjust Register code must no be null!")
        if (AJ_EVENT_APPLY.isBlank()) throw Exception("Error: Adjust Apply code must no be null!")

        //tag2025
//        FirebaseApp.initializeApp(context)

        val config = AdjustConfig(context, AJ_TOKEN, Constant_rice.Environment)

        // 日志级别
        config.setLogLevel(LogLevel.INFO)

        // 监听归因回调
        config.setOnAttributionChangedListener {
            Adjust.getAdid { adid -> covertAndSaveAttributtion(it,adid) }
        }

        // 初始化
        Adjust.initSdk(config)

        // 配置页面监听
        registerAdjustActivityLifecycle(context)

        // 获取当前归因信息
        // 每次初始化都需要重新获取，
        // 因为 setOnAttributionChangedListener 不一定回调多次

        Adjust.getAttribution { attribution ->
            Adjust.getAdid { adid -> covertAndSaveAttributtion(attribution,adid) }
        }
    }

    /**
     * 过滤Adjsut归因信息，
     * 并上传
     *
     * @param attribution AdjustAttribution
     */
    private fun covertAndSaveAttributtion(attribution: AdjustAttribution?, adid: String?) {
        attribution?.let { result ->
            //组装
            adjsutAttribution = ParamAdjustInstall()

            //adjust 归因参数
            adjsutAttribution?.let { params ->
                params.adid = adid.orEmpty()
                params.network = result.network.orEmpty()
                params.adgroup = result.adgroup.orEmpty()
                params.creative = result.creative.orEmpty()
                params.costType = result.costType.orEmpty()
                params.campaign = result.campaign.orEmpty()
                params.clickLabel = result.clickLabel.orEmpty()
                params.trackerName = result.trackerName.orEmpty()
                params.trackerToken = result.trackerToken.orEmpty()
                params.costCurrency = result.costCurrency.orEmpty()
                params.fbInstallReferrer = result.fbInstallReferrer.orEmpty()
                result.costAmount?.let { costAmount ->
                    params.costAmount = costAmount.toString()
                }

                //上报
                println("=====adjust attribution:")
                println(result)
                saveInstallInfo()
            }
        }
    }

    /**
     * 配置Adjust 页面监听
     * 如果其它模块有注册callback
     * 注意调用顺序或合并adjus
     *
     * @param context Application
     */
    fun registerAdjustActivityLifecycle(context: Application) {
        context.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(p0: Activity, p1: Bundle?) {
            }

            override fun onActivityStarted(p0: Activity) {
            }

            override fun onActivityResumed(p0: Activity) {
                Adjust.onResume()
            }

            override fun onActivityPaused(p0: Activity) {
                Adjust.onPause()
            }

            override fun onActivityStopped(p0: Activity) {
            }

            override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
            }

            override fun onActivityDestroyed(p0: Activity) {
            }
        })
    }

    /**
     * 打点
     *
     * @param event 事件名
     */
    fun addEvent(event: IAnalyticsEvent_rice) {
        try {
            when (event) {
                IAnalyticsEvent_rice.AT_REGISTER -> {
                    Adjust.trackEvent(AdjustEvent(AJ_EVENT_REGISTER))
                }
                IAnalyticsEvent_rice.AT_LOAN_APPLY -> {
                    Adjust.trackEvent(AdjustEvent(AJ_EVENT_APPLY))
                }
                else -> {}
            }
        } catch (e: Exception) {
            StringUtil_rice.printException(e)
        }
    }

    /**
     * 保存Adjust 安装信息
     */
    fun saveInstallInfo() {
        adjsutAttribution?.let { data ->
            try {
                val body = Gson().toJson(adjsutAttribution).trim()
                val path = StaticConfig_rice.getBaseUrl() + StaticConfig_rice.getCountryUrlPrefix() + Url_rice.PATH_ADJUST_INSTALL
                println("====== $path")

                HttpHelper_rice.postData(path, body)
            } catch (e: Exception) {
                StringUtil_rice.printException(e)
            }
        }
    }
}